import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:im/Pages/chatDetail.dart';
import 'package:web_socket_channel/io.dart';

Map<String, dynamic> headers = new Map();

class WebSocketProvider with ChangeNotifier {
  late IOWebSocketChannel channel;
  var connId;
  String socketUrl = "ws://localhost:8088";
  Map<String, String> headers = {
    "token":
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6IjYzNGU0YTI5YjkxYzAwMDBlYTAwMTU1MiIsImVtYWlsIjoi6YKu566xIn0.29bjgiYAJB79y2hucRP3z7NjJ6t3iG51fH81cr2rHfo"
  };
  late List<chatRecord> records;
  late String ava1;
  late String ava2;
  late IOWebSocketChannel conn;
  late String loginId;
  late String toUser;

  var msg;

  WebSocketProvider(String userId) {
    loginId = userId;
    connWebSocket(userId);
  }

  connWebSocket(String userId) {
    records = <chatRecord>[];
    ava1 = 'https://pic2.zhimg.com/v2-d2f3715564b0b40a8dafbfdec3803f97_is.jpg';
    ava2 = 'https://pic4.zhimg.com/v2-0edac6fcc7bf69f6da105fe63268b84c_is.jpg';

    records.add(chatRecord(sender: 0, content: "你吃了么", avatarUrl: ava1));
    records.add(chatRecord(sender: 1, content: "每次", avatarUrl: ava2));
    records.add(chatRecord(sender: 0, content: "吃啥", avatarUrl: ava1));
    records.add(chatRecord(sender: 1, content: "不吃\n今天不饿", avatarUrl: ava2));
    channel = IOWebSocketChannel.connect(socketUrl, headers: headers);

    channel.stream.listen((msg) async {
      // print(msg);
      var mapResult = json.decode(msg);
      // GoReceiveMsgModel receiveMsgModel = GoReceiveMsgModel.fromJson(mapResult);
      records.add(chatRecord(sender: 1, content: msg, avatarUrl: ava1));
      notifyListeners();
    });
  }
}
